package top.xia17.plugins.fast.common.security.token;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import top.xia17.plugins.fast.common.autoconfiguration.TokenProperties;
import top.xia17.plugins.fast.common.security.token.provider.TokenProvider;

import java.io.IOException;

/**
 * token认证方式的过滤器
 * @author xia17
 * @date 2020/7/17 9:50
 */
@Slf4j
@RequiredArgsConstructor
public class TokenFilter extends GenericFilterBean {

    private final TokenProvider tokenProvider;
    private final TokenProperties tokenProperties;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        if (HttpMethod.OPTIONS.matches(httpServletRequest.getMethod())){
            // OPTIONS 请求直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
        String token = this.obtainToken(httpServletRequest);
        // 对于 Token 为空的不需要去查 Redis
        if(StrUtil.isNotBlank(token)){
            // 从token中获取认证信息
            Authentication authentication = tokenProvider.getAuthentication(token);
            // 需要判断 authentication 为 null
            if (authentication != null){
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }


    /**
     * 从请求信息中获取token
     * @param request 请求信息
     * @return token
     */
    private String obtainToken(HttpServletRequest request){
        final String requestHeader = request.getHeader(tokenProperties.getTokenHeaderKey());
        if (requestHeader != null && requestHeader.startsWith(tokenProperties.getTokenPrefix())) {
            // 去除请求头中的Token前缀(Token前缀后面加上了一个空格)
            return requestHeader.replace(tokenProperties.getTokenPrefix(), "").trim();
        }
        return null;
    }







}
